import React, { useEffect, useState } from "react";
import logo from "./logo.svg";
import { Counter } from "./features/counter/Counter";
import "./App.scss";
import { Row, Col, Menu, Button, message as antdMessage, Modal } from "antd";
import { addList, fetchList } from "./service";
import axios from "axios";
import { useAppSelector } from "./app/hooks";
import { useDispatch } from "react-redux";
import { loginSuccess } from "./app/user/userSlice";

interface ListItem {
  id: string;
  avator: string;
  nickname: string;
  createTime: string;
  content: string;
  images: string[];
}

function App() {
  const [list, setList] = useState<ListItem[]>([]);
  const [content, setContent] = useState("");
  const [images, setImages] = useState<string[]>([]);
  const [isUploadImgage, setIsUploadImage] = useState(false);
  const userInfo = useAppSelector((state) => state.user.userInfo);
  const [isOpen, setIsOpen] = useState(false);
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const dispatch = useDispatch();
  const fetchData = async () => {
    const { code, data, message } = (await fetchList()).data;
    setList(data);
  };

  const publish = async () => {
    const data = {
      avator: userInfo.avator || logo,
      nickname: userInfo.nickname ||  "游客",
      createTime: new Date().toLocaleString(),
      content,
      images,
    };
    const { code, data: respData, message } = (await addList(data)).data;
    fetchData();
  };

  const onchange = (e: React.ChangeEvent<HTMLInputElement>) => {
    const files = e.target.files;
    const len = files?.length || 0;
    if (len + images.length > 6) {
      antdMessage.error("最多选择6张图片");
      return;
    }

    if (files) {
      const arr = [...files];

      arr.forEach((v) => {
        const formData = new FormData();
        formData.append("chunk", v, v.name);

        axios.post("/api/upload/image", formData).then((resp) => {
          console.log(resp.data);
          setImages((state) => {
            return [...state, resp.data.data.url];
          });
        });
      });
    }
  };

  const login = async () => {
    const resp = await axios.post("/api/login", { username, password });
    if (resp.data.code === 200) {
      dispatch(loginSuccess(resp.data.data));
      setIsOpen(false);
    } else {
      antdMessage.error("登录失败");
    }
  };
  useEffect(() => {
    fetchData();
  }, []);
  return (
    <div className="app">
      <Row>
        <Col span={4}>
          <Menu
            items={[
              {
                key: "/",
                label: "最新",
              },
              {
                key: "/set",
                label: "最新",
              },
              {
                key: "/table",
                label: "最新",
              },
              {
                key: "/user",
                label: "最新",
              },
            ]}
          ></Menu>
        </Col>
        <Col span={12}>
          <div>
            <div className="middle">
              <textarea
                className="textarea"
                value={content}
                onChange={(e) => setContent(e.target.value)}
              ></textarea>

              {isUploadImgage && (
                <div className="images-upload">
                  {images.map((v, i) => {
                    return <img src={v} key={i} alt="" />;
                  })}
                  <div className="add">
                    <span>+</span>
                    <input type="file" multiple onChange={(e) => onchange(e)} />
                  </div>
                </div>
              )}
            </div>
            <div className="bottom">
              <div className="tag">
                <span>表情</span>
                <span onClick={() => setIsUploadImage(!isUploadImgage)}>
                  图片
                </span>
                <span>链接</span>
                <span>话题</span>
              </div>
              <Button type="primary" size="large" onClick={() => publish()}>
                发布
              </Button>
            </div>
          </div>
          <div className="list">
            {list.map((v, i) => {
              return (
                <div className="list-item" key={v.id}>
                  <div className="left">
                    <img src={v.avator} alt="" />
                  </div>
                  <div className="right">
                    <h3>{v.nickname}</h3>
                    <p>{v.createTime}</p>
                    <div className="content">
                      <p>{v.content}</p>
                      <div className="image">
                        {v.images.map((v, i) => {
                          return <img src={v} alt="" key={i} />;
                        })}
                      </div>
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </Col>
        <Col span={6}>
          {userInfo.token ? (
            <div className="user">
              <div>
                <img src={userInfo.avator} alt="" className="logo" />
                <span>{userInfo.nickname}</span>
              </div>
              <div>
                <div className="user-item">
                  <span>{userInfo.hot}</span>
                  <span>沸点</span>
                </div>
                <div className="user-item">
                  <span>{userInfo.quanzi}</span>
                  <span>圈子</span>
                </div>
                <div className="user-item">
                  <span>{userInfo.about}</span>
                  <span>关注</span>
                </div>
                <div className="user-item">
                  <span>{userInfo.aboutd}</span>
                  <span>关注着</span>
                </div>
              </div>
            </div>
          ) : (
            <div className="not-login">
              <Button type="primary" onClick={() => setIsOpen(true)}>
                登录
              </Button>
              /<Button type="primary">注册</Button>
            </div>
          )}

          <div className="hot">
            <ul>
              <li>1. 天气真不错</li>
              <li>2. 天气真不错</li>
              <li>3. 天气真不错</li>
              <li>4. 天气真不错</li>
              <li>5. 天气真不错</li>
            </ul>
          </div>
        </Col>
      </Row>

      <Modal open={isOpen}>
        <input
          type="text"
          placeholder="用户名"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />
        <input
          type="text"
          placeholder="密码"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />
        <button onClick={login}>登录</button>
      </Modal>
    </div>
  );
}

export default App;
